const statusConstants = require('../constants/status');
module.exports = class extends think.Model {
  baseWhereCondition(condition) {
    return {
      status: statusConstants.valid,
      ...condition
    };
  }
  // 查找栏目
  queryAll(typeId, field = 'title,router') {
    return this.where(this.baseWhereCondition({type_id: typeId})).field(field).sort('sort desc').select();
  }
  queryByRouter(router, field = '*') {
    return this.where(this.baseWhereCondition({router})).field(field).find();
  }
  countByRouter(router, exceptId) {
    const where = {router};
    if (exceptId) {
      where.id = ['neq', exceptId];
    }
    return this.where(router).count();
  }
  countByTitle(title, exceptId) {
    const where = {title};
    if (exceptId) {
      where.id = ['neq', exceptId];
    }
    return this.where(where).count();
  }
  queryById(id, field = '*') {
    return this.where({id}).field(field).find();
  }
  countById(id) {
    return this.where({id}).count();
  }
  // 新建
  async create({
    typeId,
    title,
    router,
    parentId,
    sort,
    status
  }) {
    if (await this.countByTitle(title) === 0) {
      think.throw('栏目标题已存在');
    }
    if (await this.countByRouter(router) === 0) {
      think.throw('栏目router已存在');
    }
    if (parentId > 0) {
      if (await this.countById(parentId) === 0) {
        think.throw('父栏目不存在');
      }
    }
    this.add({
      type_id: typeId,
      create_time: think.datetime(),
      title,
      router,
      parent_id: parentId,
      sort,
      status
    });
  }
  // 修改
  async modifyById(id, {title, router, parentId, typeId, sort, status}) {
    if (title !== undefined) {
      if (await this.countByTitle(title, id) === 0) {
        think.throw('栏目标题已存在');
      }
    }
    if (router !== undefined) {
      if (await this.countByRouter(router, id) === 0) {
        think.throw('栏目router已存在');
      }
    }
    const data = think.snakeObject(think.stripUndefinedFields({title, router, parentId, typeId, sort, status}));
    return this.where({id}).update(data);
  }
};
